package cn.lixin.org.service.impl;

import cn.lixin.basic.service.impl.BaseServiceImpl;
import cn.lixin.basic.utils.MD5Utils;
import cn.lixin.basic.utils.PageList;
import cn.lixin.basic.utils.StrUtils;
import cn.lixin.org.domain.Employee;
import cn.lixin.org.mapper.EmployeeMapper;
import cn.lixin.org.query.EmployeeQuery;
import cn.lixin.org.service.IEmployeeService;
import cn.lixin.user.domain.Logininfo;
import cn.lixin.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void save(Employee employee) {
        initEmployee(employee);
        Logininfo logininfo = employee2Logininfo(employee); // 将employee复制给logininfo
        logininfoMapper.save(logininfo);// 保存 返回自增id--- logininfo 的 id = employee 的 logininfo_id
        employee.setLogininfo_id(logininfo.getId());// logininfo 的 id = employee 的 logininfo_id
        employeeMapper.save(employee);

    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        return logininfo;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        String md5 = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5);
    }

    @Override
    public void remove(Long id) {
        Employee employee = employeeMapper.loadById(id);// 查询出要删除的用户
        logininfoMapper.remove(employee.getLogininfo_id());// 先删除logininfo中的信息，因为先删除emp的话Logininfo_id()删了就找不到对应Logininfo了
        employeeMapper.remove(id);
    }

    @Override
    public void update(Employee employee) {
        super.update(employee);
    }
}
